package cn.joyfulmedia.controller.system.account;

import com.alibaba.fastjson.JSON;
import cn.joyfulmedia.common.util.Const;
import cn.joyfulmedia.common.util.page.Pagination;
import cn.joyfulmedia.entity.ExamMisAccount;
import cn.joyfulmedia.entity.ExamMisDict;
import cn.joyfulmedia.entity.ExamMisRole;
import cn.joyfulmedia.mis.service.interfaces.AccountService;
import cn.joyfulmedia.mis.service.interfaces.DictService;
import cn.joyfulmedia.mis.service.interfaces.RoleService;
import cn.joyfulmedia.mis.utils.MisResponse;
import cn.joyfulmedia.mis.utils.PassWordCreate;
import cn.joyfulmedia.shiro.ShiroSessionUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "/user")
public class AccountController {
    @Resource
    private AccountService accountService;
    @Resource
    private DictService dictService;
    @Resource
    private RoleService roleService;

    @RequestMapping("get/{id}")
    @ResponseBody
    public Object get(@PathVariable Long id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Const.STATUS, -1);
        try {
            ExamMisAccount a = accountService.selectAccountById(id);
            map.put(Const.STATUS, 1);
            map.put("data", a);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(Const.MSG, Const.DEFAULT_ERROR);
        }
        return map;
    }

    @RequestMapping("/list")
    public String list(ExamMisAccount account, Pagination pagination, Model model) {
        List<ExamMisAccount> list = accountService.listPage(account, pagination);
        model.addAttribute("list", list);
        model.addAttribute(Const.PAGINATION, pagination);
        return "/user/list";
    }

    @RequiresPermissions("sys:user:add")
    @RequestMapping("/add")
    public String add(Long id, Model model) {
        List<ExamMisDict> list = dictService.selectByColumn(Const.USER_TYPR);
        ExamMisRole r = new ExamMisRole();
        r.setDisabled(0);
        model.addAttribute("list", list);
        model.addAttribute("id", id);
        return "/user/add";
    }

    @RequestMapping("/myself")
    public String updateMyself(Model model) {
        ExamMisAccount account = ShiroSessionUtils.getLoginAccount();
        Long id = account.getId().longValue();
        List<ExamMisDict> list = dictService.selectByColumn(Const.USER_TYPR);
        ExamMisRole r = new ExamMisRole();
        r.setDisabled(0);
        model.addAttribute("list", list);
        model.addAttribute("id", id);
        return "/user/myself";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Object save(ExamMisAccount account, Long roleId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Const.STATUS, -1);
        try {
            // String message = ValidatorUtils.validate(account);
            Integer i = 0;
            if (account.getId() != null && account.getId() != 0) {
                i = accountService.updateAccountById(account);
            } else {
                ExamMisAccount a = accountService.selectByUsername(account.getUsername());
                if (a != null) {
                    map.put(Const.MSG, "用户名已存在");
                    return map;
                }
                account.setPassword(new Md5Hash(account.getPassword()).toString());
                i = accountService.saveAccount(account);
            }
            if (i > 0) {
                map.put(Const.STATUS, 0);
                map.put(Const.MSG, "保存成功");
            }
            /*
             * else { map.put(Const.MSG, message); }
			 */
        } catch (Exception e) {
            e.printStackTrace();
            map.put(Const.MSG, Const.DEFAULT_ERROR);
        }
        return map;
    }

    @RequestMapping("/editRole")
    public String editRole(Long id, HttpServletRequest request) {
        try {
            ExamMisRole role = new ExamMisRole();
            role.setDisabled(0);
            Pagination p = new Pagination();
            p.setRows(100);// 角色一般不会太多,50个应该足够了.........
            List<ExamMisRole> list = roleService.listPage(role, p);
            List<ExamMisRole> l = roleService.findByAccountId(id);
            for (ExamMisRole r : list) {
                for (ExamMisRole tmpR : l) {
                    if (tmpR.getId() != null && r.getId() != null && tmpR.getId().intValue() == r.getId().intValue()) {
                        r.setChecked(Const.CHECKED);
                        break;
                    }
                }
            }
            request.setAttribute("list", list);
            request.setAttribute("id", id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/user/editRole";
    }


    @RequestMapping("/saveRole")
    public String saveRole(Long id, Long[] rid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Const.STATUS, -1);
        try {
            roleService.delRoleBYId(id);
            roleService.bathSaveRole(rid, id);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(Const.MSG, Const.DEFAULT_ERROR);
        }
        return "redirect:/user/list";
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public Object updatePwd(ExamMisAccount account) {
        Map<String, Object> map = MisResponse.getSuccessMap();
        try {
            PassWordCreate pwc = new PassWordCreate();
            String pwd = pwc.createPassWord(8);
            account.setPassword(DigestUtils.md5Hex(pwd));
            account.setId(account.getId());
            account.setForceChgPwd(0);
            System.out.println("请求更新密码的参数为：" + JSON.toJSONString(account));
            int i = accountService.updateAccountById(account);
            if (i > 0) {
                map.put("pwd", pwd);
            } else {
                MisResponse.updateResponseMap(map, -1, "更新用户登录密码失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put(Const.MSG, Const.DEFAULT_ERROR);
        }
        return map;
    }

    @RequestMapping("/del")
    @ResponseBody
    public Object delUser(ExamMisAccount account) {
        Map<String, Object> map = MisResponse.getSuccessMap();
        try {
            int i = accountService.delUser(account.getId());
            if (i <= 0) {
                MisResponse.updateResponseMap(map, -1, "删除用户失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put(Const.MSG, Const.DEFAULT_ERROR);
        }
        return map;
    }
}
